<template>
  <view class="container">
    <scroll-view scroll-y class="chat-window">
      <view
        v-for="(item, index) in messages"
        :key="index"
        class="msg-item"
        :class="item.from"
      >
        <view v-if="item.from === 'bot'" class="avatar">
          <image src="/static/cnx.png" class="avatar-img" />
        </view>
		
		<view v-if="item.from === 'user'" class="avatar">
		  <image src="/static/user.jpg" class="avatar-img" />
		</view>
        
        <view class="bubble" :class="item.from">{{ item.content }}</view>
      </view>
    </scroll-view>

    <view class="input-bar">
      <input v-model="inputText" placeholder="请输入消息" class="input" />
      <button type="primary" size="small" @click="sendMessage" class="btn">发送</button>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue'

const messages = ref([
  { from: 'bot', content: '你好，我是AI助手，有什么可以帮你？' }
])
const inputText = ref('')

// 发送消息到后端
const sendMessage = async () => {
  if (!inputText.value.trim()) return

  // 发送用户消息
  messages.value.push({ from: 'user', content: inputText.value })

  // 临时占位符，显示“正在输入...”
  messages.value.push({ from: 'bot', content: '正在输入...' })

  const userMessage = inputText.value
  inputText.value = ''

  // 请求后端API，获取AI回复
  const response = await uni.request({
    url: 'http://localhost:8080/api/chat',  // 后端接口URL
    method: 'POST',
    data: { message: userMessage },
    header: {
      'Content-Type': 'application/json',
    },
  })

  if (response[1].statusCode === 200) {
    const aiResponse = response[1].data.reply
    messages.value.push({ from: 'bot', content: aiResponse })
  } else {
    messages.value.push({ from: 'bot', content: 'AI回复出错，请稍后再试。' })
  }

  // 移除“正在输入...”占位消息
  messages.value = messages.value.filter((item) => item.content !== '正在输入...')
}
</script>

<style scoped>
.container {
  height: 86vh;
  display: flex;
  flex-direction: column;
  background-color: #121212;
}

.chat-window {
  flex: 1;
  margin-top: 5px;
}

.msg-item {
  display: flex;
  align-items: flex-end;
  margin-bottom: 20rpx;
}

.msg-item.bot {
  flex-direction: row;
}

.msg-item.user {
  flex-direction: row-reverse;
}

.avatar {
  width: 60rpx;
  height: 60rpx;
  margin: 0 10rpx;
}

.avatar-img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}

.bubble {
  max-width: 60%;
  padding: 20rpx;
  border-radius: 20rpx;
  margin: 0 10rpx;
  word-wrap: break-word;
  color: #fff;
}

.bubble.bot {
  background-color: #2a2a2a;
}

.bubble.user {
  background-color: #0ff;
  color: #000;
}

.input-bar {
  display: grid;
  grid-template-columns: 3fr 1fr;
  gap: 10rpx;
  padding: 10rpx;
  background-color: #1e1e1e;
}

.input {
  padding: 20rpx;
  border-radius: 10rpx;
  border: 1px solid #0ff;
  background-color: #2a2a2a;
  color: #ffffff;
}

.btn {
  border-radius: 10rpx;
  background-color: #00ffff;
  color: #000000;
  text-align: center;
}
</style>
